package org.gap.jseed.injection.annotation;

import org.gap.jseed.Builder;

/**
 * Ensure that only one instance of the object is instantiated.
 * @author gpelcha
 *
 * @param <E>
 */
public class SingletonBuilder<E> implements Builder<E> {

	private final Builder<E> builder;
	private E singleton = null;
	private Class<? extends E> service;
	
	public SingletonBuilder(Builder<E> builder, Class<? extends E> service) {
		this.builder = builder;
		this.service = service;
	}

	@Override
	public E createInstance() {
		if (singleton == null) {
			E result = builder.createInstance();
			if (hasSingletonAnnotation(service)) {
				singleton = result;
			} else {
				return result;
			}
		}
		return singleton;
	}

	private boolean hasSingletonAnnotation(Class<?> clazz) {
		if (clazz.isAnnotationPresent(Singleton.class)) {
				return true;
		}
		return false;
	}

	@Override
	public Class<? extends E> getType() {
		return builder.getType();
	}

}
